<template>
    <div class="demo-tree">
        <div class="custom-tree-container">
            <div class="block">
                <p>使用 tree</p>
                <!--
                http://element-cn.eleme.io/#/zh-CN/component/tree
                Attributes  props
                        :load="loadNode"
                        :data="treeData"
            <el-tree
                        :props="props1"
                        :load="loadNode"
                        show-checkbox   节点是否可被选择
                        lazy
                        @node-click="handleNodeClick"
                        @check-change="handleCheckChange"

                        node-key="id"
                        default-expand-all                是否默认展开所有节点
                        :expand-on-click-node="false"     点击节点的时候展开或者收缩节点
                        @node-drag-start="handleDragStart"
                        @node-drag-enter="handleDragEnter"
                        @node-drag-leave="handleDragLeave"
                        @node-drag-over="handleDragOver"
                        @node-drag-end="handleDragEnd"
                        @node-drop="handleDrop"
                        draggable
                        :allow-drop="allowDrop" 拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
                        :allow-drag="allowDrag" 判断节点能否被拖拽
                          @node-drag-over="handleDragOver"

                >-->
                <el-tree
                        :props="props1"
                        show-checkbox
                        :lazy="true"
                        :load="loadNode"
                        node-key="id"
                        default-expand-all
                        expand-on-click-node
                        :render-after-expand="false"

                        @node-click="handleNodeClick"
                        @check-change="handleCheckChange"
                        @node-drag-start="handleDragStart"
                        @node-drag-enter="handleDragEnter"
                        @node-drag-leave="handleDragLeave"
                        @node-drag-end="handleDragEnd"
                        @node-drop="handleDrop"
                        draggable
                >
<span class="custom-tree-node" slot-scope="{ node, data }">
  <span><i v-show="node.data.leaf" class="el-icon-info"> </i>&nbsp;{{ node.label }}</span>
  <span class="tree-diy">{{ node.id }}</span>
  <span class="tree-diy">{{ node.isLeaf }}</span>
  <span class="tree-diy">{{ node.data.id }}</span>
  <span class="tree-diy">{{ node.data.groupName }}</span>
  <span>
    <template v-if="node.data.leaf">
        <i class="el-icon-edit" @click.stop="() => editResource(data)"></i>
    &nbsp;&nbsp;<i class="el-icon-delete" @click.stop="() => removeR(node, data)"></i>
    </template>
    <template v-else>
      <i v-if="node.data.groupEnd" class="el-icon-circle-plus-outline"
         @click.stop="() => createLeaf(data)"></i>
      &nbsp;&nbsp;<i class="el-icon-plus" @click.stop="() => createG(data)"></i>
      &nbsp;&nbsp;<i class="el-icon-edit" @click.stop="() => editGroup(data)"></i>
      &nbsp;&nbsp;<i class="el-icon-delete" @click.stop="() => removeG(node, data)"></i>
        <!--<el-button  icon="el-icon-plus" circle type="success" size="mini" @click="() => append(data)"> </el-button>-->
    </template>
  </span>
</span>
                </el-tree>
            </div>
        </div>
        <!---->
        <el-dialog :title="textMap2[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px"
                     style='width: 450px; margin-left:50px;'>


                <el-form-item label="资源名" prop="resourceName">
                    <el-input v-model="leafTemp.resourceName"></el-input>
                </el-form-item>
                <el-form-item label="资源类型" prop="resourceType">
                    <el-select v-model="leafTemp.resourceType" placeholder="请选择">
                        <el-option
                                v-for="item in resourceType"
                                :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>

                    <!--<el-input v-model="leafTemp.resourceType"></el-input>-->
                </el-form-item>
                <el-form-item label="请求方法" prop="requestMethod">
                    <el-select v-model="leafTemp.requestMethod" placeholder="请选择">
                        <el-option
                                v-for="item in requestMethod"
                                :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>
                    <!--<el-input v-model="leafTemp.requestMethod"></el-input>-->
                </el-form-item>
                <el-form-item label="资源码" prop="resourceCode" placeholder="resourceCode">
                    <el-input v-model="leafTemp.resourceCode"></el-input>
                </el-form-item>
                <el-form-item label="图标链接" prop="icon" placeholder="icon">
                    <el-input v-model="leafTemp.icon"></el-input>
                </el-form-item>
                <el-form-item label="标记" prop="tag" placeholder="tag">
                    <el-input v-model="leafTemp.tag"></el-input>
                </el-form-item>
                <el-form-item label="url" prop="url">
                    <el-input v-model="leafTemp.url"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createLeafSubmit" id="cfmbtm1">确定
                </el-button>
                <el-button v-else type="primary" @click="editLeaf" id="cfmbtm2">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    //http://extjs.org.cn/
    //http://element-cn.eleme.io/#/zh-CN/component/tree
    import {fetchList, fetchGet, createOne, deleteOne, getOne, rolesAll, updateOneNoId} from '@/api/common'
    import {disableBtn, df, $err, $suc, ERRS, SUCS} from '@/utils'

    export default {
        inject: ['reload'],
        name: 'tree',
        props: {
            /*        fdata: {
                        type: Array,
                        default() {
                            return []
                        }
                    },*/
        },
        data() {
            /*const data = ;*/
            return {
                // treeData:this.fdata,
                url: 'security/resourceGroups',
                urlLeaf: 'security/resources',
                treeData: [],
                props1: { //自定义数组属性 leaf 叶子节点
                    id: 'id',
                    label: 'groupName',
                    children: 'children',
                    isLeaf: 'groupEnd',
                },
                count: 3,
                //弹出层
                dialogFormVisible: false,
                dialogStatus: '',
                listLoading: true,
                textMap: {
                    update: '编辑资源组',
                    create: '添加资源组'
                },
                textMap2: {
                    update: '编辑资源',
                    create: '添加资源'
                },
                requestMethod: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'TRACE', 'ALL', 'NOAPI'],
                resourceType: ['WEB_MENU', 'WEB_BUTTON', 'ANDROID_MENU', 'ANDROID_BUTTON', 'IOS_MENU', 'IOS_BUTTON',],
                temp: {},
                leafTemp: {},
                template: {
                    id: undefined,
                    roleName: '',
                    roleCode: ''
                },
                rules: {
                    roleName: [
                        {required: true, message: '请输入角色名', trigger: 'blur'}
                    ],
                    roleCode: [
                        {required: true, message: '请输入标记名', trigger: 'change'},
                    ]
                }
                // data5: JSON.parse(JSON.stringify(this.trees))
            }
        },

        mounted() {
            this.getList();
            // this.initInfo();
        },
        computed: {},
        methods: {
            /*  ----------curd ----------- */
            //添加资源(叶子)
            appendLeaf(data) {
                const newChild = {
                    id: ++this.count, name: 'testtest', children: [],
                    groupEnd: false
                };
                if (!data.children) {
                    this.$set(data, 'children', []);
                }
                data.children.push(newChild);
                data.groupEnd = false;

                df('11append', this.treeData)
            },
            //添加资源组
            appendG(data) {
                df(222, data)
                const newChild = {
                    id: ++this.count, name: 'testtest', children: [],
                    groupEnd: true
                };
                if (!data.children) {
                    this.$set(data, 'children', []);
                }
                data.children.push(newChild);
                data.groupEnd = false;

                df(222, data)
                df(222, this.treeData)
            },

            createG() {
                this.resetTemp();
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            //添加提交
            createGsubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        disableBtn('cfmbtm1');
                        createOne(this.url, this.temp).then(response => {
                            this.reload();
                            this.dialogFormVisible = false
                            succ('创建成功')
                        })
                    }
                })
            },

            createLeaf(dat) {
                console.log(257,dat)
                this.leafTemp = {
                    groupId:dat.id,
                    id:"",
                    icon: "",
                    requestMethod: "",
                    resourceType: "",
                    resourceCode: "",
                    resourceName: "",
                    tag: "",
                    url: ""
                };
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            //添加提交
            createLeafSubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        disableBtn('cfmbtm1');
                        console.log(277,this.leafTemp)
                        let lf=this.leafTemp;
                        const params = new URLSearchParams();
                        params.append('icon', lf.icon);
                        params.append('requestMethod', lf.requestMethod);
                        params.append('resourceType', lf.resourceType);
                        params.append('resourceCode', lf.resourceCode);
                        params.append('resourceName', lf.resourceName);
                        params.append('tag', lf.tag);
                        params.append('url', lf.url);
                        createOne(`security/resources/groups/${this.leafTemp.groupId}/resources`,params).then(response => {
                            this.reload();
                            this.dialogFormVisible = false
                            succ('创建成功')
                        })
                    }
                })
            },
            removeG(node, data) {
                df('rm G', node.data.id, node)
                this.remove(node, data, ' 资源组及子资源 ', this.url)
            },
            removeR(node, data) {
                df('rm R', node, data)
                this.remove(node, data, ' 资源 ', this.urlLeaf)
            },
            remove(node, data, msg, url) {
                this.$msgbox({
                    message: `确定要删除该${msg}吗?`,
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(action => {
                    df(5435345)
                    deleteOne(url, {id: node.data.id}).then(res => {
                        df(5435345, res)
                        if (res.data.code === 0) {
                            $suc('删除成功')
                            this.reload()
                        } else {
                            $err(res.data.message)
                        }
                    })
                });
            },

            //详情修改
            editLeaf(data) {
                df('editResource', data);
                /*            this.temp=row;
                            this.dialogFormVisible = true;
                            this.$nextTick(() => {
                                this.$refs['dataForm'].clearValidate()
                            })*/
            },
            editGroup(data) {
                df('editGroup', data);
                return false;
            },
             getList() {
                 this.listLoading = true;
                 // fetchList(`security/resourceGroups/root`).then(response => {
                 // fetchList(`security/resourceGroups`).then(response => {
                 fetchList(`security/resourceGroups/resourceRG/all`).then(response => {
                     let data=response.data;
                     console.log(100,data)
                     if(data.code==0){
                         // return data.data
                         this.treeData= data.data

                         this.$nextTick(function(){
                             console.log('v-for渲染已经完成')
                             // this.loadNode()
                         })
                     }else{
                         err(data.message)
                     }
                     this.listLoading = false
                 })
             },
            handleCheckChange(data, checked, indeterminate) {
                console.log(data, checked, indeterminate);
            },
            //节点点击事件
            handleNodeClick(data) {
                console.log(data);
                // this.append(data)
            },
            loadNode(node, resolve) {

                console.log('loadNode', node);
                //1级组节点
                if (node.level === 0) {
                    fetchList(`security/resourceGroups/root`).then(response => {
                        // fetchList(`security/resourceGroups/resourceRG/all`).then(response => {
                        let data = response.data;
                        // console.log(100,data)
                        if (data.code == 0) {
                            this.treeData = data.data
                            // console.log(555,this.treeData)
                            // node.level=
                            /*                        groupEnd: true
                                                    groupName: "用户管理"
                                                    groupSort: 0
                                                    id: "2c9080b6670af0e101670af101a80008"
                                                    level: 1*/
                            return resolve(data.data);
                        } else {
                            err(data.message)
                        }
                    })
                } else {
                    //组子节点(含子节点)
                    if (node.data.groupEnd === false) {

                        fetchList(`security/resourceGroups/parentId/${node.data.id}`).then(response => {
                            let data = response.data;
                            // console.log(110,data)
                            if (data.code == 0) {
                                let da = data.data

                                console.log(111, this.treeData)
                                console.log(112, node)
                                resolve(data.data); //加载下级数据!
                            } else {
                                err(data.message)
                                return resolve([]);
                            }
                        })
                    } else if (node.data.groupEnd === true) {
                        // df(220,node)
                        //组子节点(叶子)
                        //叶子调用资源
                        fetchList(`security/resources/groups/${node.data.id}`).then(response => {
                            let data = response.data;
                            // console.log(221,data)
                            if (data.code == 0) {
                                let da = data.data
                                let ret = data.data.map((v, index) => {
                                    v.groupName = v.resourceName
                                    v.leaf = true
                                    return v
                                });
                                // console.log(222,ret)

                                return resolve(ret); //加载下级数据!
                            } else {
                                err(data.message)
                                return resolve([]);
                            }
                        })
                        resolve([]);
                    } else {
                        // df(130,node)
                        return resolve([]);

                    }
                }


            },
            /*loadNode(node, resolve) {
                console.log(node);
                if (node.level === 0) {
                    // let data=this.getList();
                    // return resolve(data);
                    // return resolve([{id:1, groupName: 'region1' }, {id:2,  groupName: 'region2' }]);
                }
                if (node.level > 3) return resolve([]);

                var hasChild;
                if (node.data.groupName === 'region1') {
                    hasChild = true;
                } else if (node.data.groupName === 'region2') {
                    hasChild = false;
                } else {
                    hasChild = Math.random() > 0.5;
                }

                setTimeout(() => {
                    var dat;
                    if (hasChild) {
                       let cnt= ++this.count
                        dat = [{
                            id:cnt,
                            groupName: 'zone' + cnt
                        }, {
                            id:cnt,
                            groupName: 'zone' + cnt
                        }];
                    } else {
                        dat = [];
                    }

                    resolve(dat);
                }, 500);
            },*/

            /*拖动*/
            handleDragStart(node, ev) {
                console.log('drag start', node);
            },
            handleDragEnter(draggingNode, dropNode, ev) {
                console.log('tree drag enter: ', dropNode.label);
            },
            handleDragLeave(draggingNode, dropNode, ev) {
                console.log('tree drag leave: ', dropNode.label);
            },
            handleDragEnd(draggingNode, dropNode, dropType, ev) {
                console.log('tree drag end: ', dropNode && dropNode.label, dropType);
            },
            handleDrop(draggingNode, dropNode, dropType, ev) {
                console.log('tree drop: ', dropNode);
                console.log('tree drop: ', dropNode.label, dropType);
            },
            allowDrop(draggingNode, dropNode, type) {
                df(867, draggingNode)
                return false;
                /*            if (dropNode.data.label === '二级 3-1') {
                                return type !== 'inner';
                            } else {
                                return true;
                            }*/
            },
            allowDrag(draggingNode) {
                df(867, draggingNode)
                return draggingNode.data.groupName.indexOf('查询用户') === -1;
            }
        },
    }
</script>

<style scoped>

    .demo-tree {
        background: #f6f6f6
    }

    .demo-tree .buttons, .demo-tree .filter-tree {
        margin-top: 20px
    }

    .demo-tree .custom-tree-container {
        display: -ms-flexbox;
        display: flex;
        margin: 0px
    }

    .demo-tree .block {
        -ms-flex: 1;
        flex: 1;
        padding: 8px 24px 24px
    }

    .demo-tree .block > p {
        text-align: center;
        margin: 0;
        line-height: 4
    }

    .demo-tree .block:first-child {
        border-right: 1px solid #eff2f6
    }

    .demo-tree .custom-tree-node {
        -ms-flex: 1;
        flex: 1;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -ms-flex-pack: justify;
        justify-content: space-between;
        font-size: 16px;
        padding: 8px;
    }

    .demo-tree .el-tree {
        border: 1px solid #fbd7ff;
        border-radius: 5px;
        padding: 10px;
    }

    .tree-diy {
    }
</style>
